package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.nursing.websocket.WebSocketServer;
import com.zzyl.system.mapper.SysUserRoleMapper;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 过滤数据
     */
    @Override
    public void alertFilter() {

        // 如果没有启用的报警规则，直接不需要过滤
        Long count = this.lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (count <= 0) {
            return;
        }

        List<List<DeviceData>> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);

        if (ObjectUtil.isEmpty(values)) {
            return;
        }
        List<DeviceData> big = new ArrayList<>();
        for (List<DeviceData> value : values) {
            big.addAll(value);
        }
        big.forEach(v -> {
            alertFilter(v);
        });

    }

    /**
     * 过滤数据
     *
     * @param deviceData 上报的数据
     */
    private void alertFilter(DeviceData deviceData) {

        // 判断时间是否超过1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        Long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between >= 60) {
            return;
        }

        // 若alertRule的设备id为-1，则查询产品下的所有设备
        List<AlertRule> list = this.lambdaQuery().eq(AlertRule::getIotId, -1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .list();

        // 不为-1， 直接准备对应报警规则数据
        List<AlertRule> list2 = this.lambdaQuery().eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .list();

        list.addAll(list2);

        if (CollUtil.isEmpty(list)) {
            return;
        }

        list.forEach(v -> deviceDataAlarmHandler(v, deviceData));

    }

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    /**
     * 获取每一条规则和对应的报警数据进行匹配
     *
     * @param rule       报警规则  持续周期  和   沉默周期     操作符  阈值
     * @param deviceData 上报的数据
     */
    private void deviceDataAlarmHandler(AlertRule rule, DeviceData deviceData) {

        String iotId = deviceData.getIotId();
        String iotCountKey = CacheConstants.IOT_COUNT_ALERT + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        // 判断是否在生效时间内
        String alertEffectivePeriod = rule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime   = LocalTime.parse(split[1]);
        LocalTime curTime = deviceData.getAlarmTime().toLocalTime();
        if (curTime.isBefore(startTime)) {
            return;
        }
        if (curTime.isAfter(endTime)) {
            return;
        }

        // 判断数据阈值
        String dataValue = deviceData.getDataValue();
        String operator = rule.getOperator();

        //Double d = Double.parseDouble(dataValue);
        Double d = Double.valueOf(dataValue);
        Double value = rule.getValue();
        if (operator.contains(">")) {
            Integer compare = Double.compare(d, value);
            if (compare < 0) {
                redisTemplate.delete(iotCountKey);
                return;
            }
            if (compare == 0) {
                if (!operator.contains("=")) {
                    redisTemplate.delete(iotCountKey);
                    return;
                }
            }
        }

        if (operator.contains("<")) {
            Integer compare = Double.compare(d, value);
            if (compare > 0) {
                redisTemplate.delete(iotCountKey);
                return;
            }
            if (compare == 0) {
                if (!operator.contains("=")) {
                    redisTemplate.delete(iotCountKey);
                    return;
                }
            }
        }

        // 校验沉默周期
        String silentKey = CacheConstants.IOT_SILENT_ALERT + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        Object o = redisTemplate.opsForValue().get(silentKey);
        // 过期失效就自动删除key, 所以有这个key就代表进入了沉默周期
        if (!ObjectUtil.isEmpty(o)) {
            return;
        }

        // 判断持续周期
        Integer round = (Integer) redisTemplate.opsForValue().get(iotCountKey);
        if (ObjectUtil.isNull(round)) {
            redisTemplate.opsForValue().increment(iotCountKey);
            return;
        }
        if (round + 1 < rule.getDuration()) {
            redisTemplate.opsForValue().increment(iotCountKey);
            return;
        }

        // 大于等于redis报警数，触发真正的报警
        // 删除redis报警key
        redisTemplate.delete(iotCountKey);
        redisTemplate.opsForValue().setIfAbsent(silentKey, "1", rule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 是否是老人数据
        List<Long> ids = new ArrayList<>();
        if (rule.getAlertDataType() == 0) {
            // 是否是固定设备, 就是睡眠检测带
            if (deviceData.getLocationType() == 1) {
                ids = deviceMapper.selectNursingIdByIotIdWithBed(rule.getIotId());
            }
            // 不是，就是智能手表
            if (deviceData.getLocationType() == 0) {
            }
        }

        // 不是老人数据，那只能是烟雾报警器
        if (rule.getAlertDataType() == 1) {
            ids = sysUserRoleMapper.selectByRoleName("维修工");
        }

        List<Long> res = sysUserRoleMapper.selectByRoleName("超级管理员");
        Collection<Long> allIds = CollUtil.addAll(ids, res);
        List<AlertData> alertData = insertAlertData(allIds, rule, deviceData);

        websocketNotity(alertData.get(0), rule, allIds);

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * websocket推送消息
     *
     * @param alertData
     * @param rule
     * @param allUserIds
     */
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);

        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);

    }

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 批量保存报警数据
     *
     * @param allUserIds
     * @param rule
     * @param deviceData
     */
    private List<AlertData> insertAlertData(Collection<Long> allUserIds, AlertRule rule, DeviceData deviceData) {

        //属性拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        //属性补全
        alertData.setAlertRuleId(rule.getId());
        //报警原因
        alertData.setAlertReason(rule.getFunctionName() + rule.getOperator() + rule.getValue() + "，持续" + rule.getDuration() + "分钟，沉默" + rule.getAlertSilentPeriod() + "分钟");
        //状态
        alertData.setStatus(0);
        //类型
        alertData.setType(rule.getAlertDataType());

        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(list);
        return list;
    }

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
